﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Xml.Xsl;

namespace CodeUtils
{
    public class Email
    {
        #region DECLARATIONS AND ASSINMENTS
        private static string senderID, senderName, senderPassword;
        private static string strHostName;
        private static int portNumber;
        #endregion

        #region Initialize Variables
        // simple and quick way to send an email to admin
        // values hard coded
        // 11/10/2011
        public void QuickMail(string ToEmail, string FromMail, string Subject, string MessageBody)
        {
            MailMessage mm = new MailMessage();
            mm.IsBodyHtml = true;
            mm.Body = MessageBody;
            mm.To.Add(new MailAddress(ToEmail));
            mm.From = new MailAddress(FromMail);
            mm.Subject = Subject;
            SmtpClient sm = new SmtpClient();
            sm.Credentials = new System.Net.NetworkCredential("varun.maggo@iBtions.com", "BackSpace999");
            sm.Port = 587;
            sm.Host = "smtp.gmail.com";
            sm.EnableSsl = true;
            sm.Send(mm);
        }

        public static void InitializeVariables()
        {
            strHostName = ConfigurationManager.AppSettings["HostName"].ToString();
            senderID = ConfigurationManager.AppSettings["SenderId"].ToString();

            // for compatibility the line is written at the end of the function inside try catch to still intialize all other variables
            // so that the code will not break for password and try to send email if the smtp server is not authenticated.
            //senderPassword = ConfigurationManager.AppSettings["SenderPassword"].ToString();
            senderName = ConfigurationManager.AppSettings["SenderName"].ToString();
            portNumber = Convert.ToInt32(ConfigurationManager.AppSettings["PortNumber"]);
            try
            {
                senderPassword = ConfigurationManager.AppSettings["SenderPassword"].ToString();
            }
            //catch (Exception ex)
            catch
            {
                //
            }

        }

        #endregion

        public bool SendNewPasswordMail(string recepientID, string recepientName, string password)
        {
            bool mailSent = false;
            string strMessageSubject, strMessageBody;
            strMessageSubject = ConfigurationManager.AppSettings["NewPasswordMessageSubject"].ToString();
            strMessageBody = ConfigurationManager.AppSettings["NewPasswordMessageBody"].ToString();

            mailSent = Sendmail(recepientID, recepientName, password, strMessageSubject, strMessageBody);

            return mailSent;
        }

        public bool SendLostPasswordMail(string recepientID, string recepientName, string password)
        {
            bool mailSent = false;
            string strMessageSubject, strMessageBody;
            strMessageSubject = ConfigurationManager.AppSettings["LostPasswordMessageSubject"].ToString();
            strMessageBody = ConfigurationManager.AppSettings["LostPasswordMessageBody"].ToString();

            mailSent = Sendmail(recepientID, recepientName, password, strMessageSubject, strMessageBody);
            return mailSent;
        }

        public bool SendExternalMail(string mailTo, string mailSubject, string mailBody, List<MailAddress> ccGroup)
        {
            try
            {
                InitializeVariables();

                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(senderID, senderName);

                msg.To.Add(mailTo);

                if (ccGroup != null && ccGroup.Count > 0)
                {
                    foreach (MailAddress ccItem in ccGroup)
                    {
                        msg.CC.Add(ccItem);
                    }
                }

                msg.Subject = mailSubject;
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Body = mailBody;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.IsBodyHtml = false;

                SmtpClient client = new SmtpClient();
                client.Host = strHostName;
                client.Port = portNumber;

                client.Send(msg);
            }
            catch (SmtpException ex)
            {
                ex.Message.ToString();
                return false;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return false;
            }
            return true;
        }

        public bool Sendmail(string recepientID, string recepientName, string password, string strMessageSubject, string strMessageBody)
        {
            try
            {
                //InitializeVariables();

                MailMessage msg = new MailMessage();
                senderID = System.Configuration.ConfigurationManager.AppSettings["SenderId"].ToString();
                senderName = System.Configuration.ConfigurationManager.AppSettings["SenderName"].ToString();

                msg.From = new MailAddress(senderID, senderName);
                msg.To.Add(recepientID);
                msg.Subject = strMessageSubject;
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Body = "User ID= " + recepientName;
                msg.Body += "\nPassword= " + password;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.IsBodyHtml = false;

                SmtpClient client = new SmtpClient();
                System.Configuration.AppSettingsReader oAppSettingReader = new System.Configuration.AppSettingsReader();

                if (oAppSettingReader.GetValue("SMTP_MAIL_SVR_USE_AUTH", typeof(string)).ToString().ToUpper().Equals("Y"))
                {
                    client.Credentials = new System.Net.NetworkCredential(Convert.ToString(oAppSettingReader.GetValue("SMTP_MAIL_SVR_USR", typeof(string))), Convert.ToString(oAppSettingReader.GetValue("SMTP_MAIL_SVR_PWD", typeof(string))));
                    client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    if (oAppSettingReader.GetValue("SMTP_MAIL_SVR_USE_SSL", typeof(string)).ToString().ToUpper().Equals("Y"))
                    {
                        client.EnableSsl = true;
                    }
                    else
                    {
                        client.EnableSsl = false;
                    }
                }
                client.Host = Convert.ToString(oAppSettingReader.GetValue("SMTP_MAIL_SVR_HOST", typeof(string)).ToString());
                client.Port = Convert.ToInt16(oAppSettingReader.GetValue("SMTP_MAIL_SVR_PORT", typeof(string)).ToString());
                oAppSettingReader = null;

                client.Send(msg);
            }
            catch (SmtpException ex)
            {
                ex.Message.ToString();
                return false;
            }
            catch
            {
                return false;
            }
            return true;
        }

        //private static void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        //{
        //-----------------------------------------------------
        //client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
        //    object userState = msg;
        //-----------------------------------------------------
        //    MailMessage mail = (MailMessage)e.UserState;
        //    string subject = mail.Subject;

        //    if (e.Cancelled)
        //    {
        //        string cancelled = string.Format("[{0}] Send canceled.", subject);
        //    }
        //    if (e.Error != null)
        //    {
        //        string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
        //    }

        //}

        /// <summary>
        /// To send mail with attachments and cc as well as bcc address
        /// </summary>
        /// <param name="toAddress"></param>
        /// <param name="ccAddress"></param>
        /// <param name="bccAddress"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="isHtml"></param>
        /// <param name="fromAddress"></param>
        /// <param name="fromPassword"></param>
        /// <param name="fileName"></param>
        public void SendEmail(string toAddress, string ccAddress, string bccAddress, string subject, string body, bool isHtml, string fromAddress, string fromPassword, string fileName)
        {
            try
            {
                MailMessage message = new MailMessage();
                message.IsBodyHtml = true;

                message.Body = body;
                message.To.Add(new MailAddress(toAddress));
                message.From = new MailAddress(fromAddress);
                message.Subject = subject;
                SmtpClient sm = new SmtpClient();

                sm.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);

                if (ccAddress.Length > 0)
                {
                    message.CC.Add(ccAddress);
                }
                if (bccAddress.Length > 0)
                {
                    message.Bcc.Add(bccAddress);
                }

                sm.Port = 587;
                sm.Host = "smtp.gmail.com";
                sm.EnableSsl = true;

                //for attachment
                //In windows....use OpenFileDialog or textbox etc controls where the user can specify path for attachments
                //In Web ....use Fileupload control or textbox etc to specify attachments path
                Attachment attachment = new Attachment(fileName);
                message.Attachments.Add(attachment);

                sm.Send(message);

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                // return false;
            }
        }
     
    }
}
